package com.lzcu.maoyan.mapreduce.mapreduce.reduce;

import com.lzcu.maoyan.mapreduce.mapreduce.unit.MovieLeadingActorWritable;
import com.lzcu.maoyan.mapreduce.mapreduce.unit.MovieTypeWritable;
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.NullWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Reducer;

import java.io.IOException;
import java.util.Arrays;

/**
 * @author WangLiang
 * @date `2024/4/27`
 */
public class MovieLeadingActorReduce extends Reducer<Text, Text, NullWritable, MovieLeadingActorWritable> {

    @Override
    protected void reduce(Text key, Iterable<Text> values, Context context)
            throws IOException, InterruptedException {
        long maxTotal = 0L;
        int movieCount = 0;
        StringBuilder movieName = new StringBuilder();
        for (Text value : values) {
            String[] valueList = value.toString().split("\001");
            if (valueList.length >= 2) {
                movieName.append(valueList[0]).append("\001");
                maxTotal += Long.parseLong(valueList[1]);
                movieCount += 1;
            }
        }
        String delimiter = "\001";

        String movie = "";
        if (movieName.toString().endsWith(delimiter)) {
            movie = movieName.substring(0, movieName.toString().length() - delimiter.length()).toString();
        }
        MovieLeadingActorWritable movieLeadingActorWritable = new MovieLeadingActorWritable();
        movieLeadingActorWritable.setLeadingActor(key.toString());
        movieLeadingActorWritable.setBoxOfficeTotal(maxTotal);
        movieLeadingActorWritable.setMovieName(movie);
        movieLeadingActorWritable.setMovieCount(movieCount);
        context.write(NullWritable.get(), movieLeadingActorWritable);
    }
}
